package com.example.opengldemo._06_;

import android.content.Context;
import android.opengl.GLES30;
import android.opengl.GLSurfaceView;
import android.view.MotionEvent;

import com.example.opengldemo._05_.Point_Line_Shape;
import com.example.opengldemo._05_.SixShape;
import com.example.opengldemo.util.MatrixState;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class _6MySurfaceView extends GLSurfaceView {
    private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
    private MyRenderer mRenderer;
    public float lightOffset ;
    private RotateThread thread;

    public _6MySurfaceView(Context context) {
        super(context);
        this.setEGLContextClientVersion(3);
        mRenderer = new MyRenderer();
        this.setRenderer(mRenderer);
        this.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
    }



    class MyRenderer implements Renderer {
        Ball cube;

        @Override
        public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) {
            GLES30.glClearColor(0.5f, 0.5f, 0.5f, 1f);
            cube = new Ball(_6MySurfaceView.this);
            GLES30.glEnable(GLES30.GL_DEPTH_TEST);
            MatrixState.setInitStack();
            thread = new RotateThread();
            thread.start();
        }

        @Override
        public void onSurfaceChanged(GL10 gl10, int i, int i1) {
            GLES30.glViewport(0, 0, i, i1);
            float ratio = (float) i / i1;
            MatrixState.setProjectFrustum(-ratio, ratio, -1, 1, 1, 5);
            MatrixState.setCamera(0, 0, 2f, 0, 0, 0f, 0f, 1.0f, 0.0f);

        }

        @Override
        public void onDrawFrame(GL10 gl10) {
            GLES30.glClear(GLES30.GL_DEPTH_BUFFER_BIT | GLES30.
                    GL_COLOR_BUFFER_BIT);
            MatrixState.setLightDirection(lightOffset, 0, 1.5f);
            MatrixState.pushMatrix();
            MatrixState.pushMatrix();
            MatrixState.translate(-1.2f, 0, 0);
            cube.drawSelf();
            MatrixState.popMatrix();
            MatrixState.pushMatrix();
            MatrixState.translate(1.2f, 0, 0);
            cube.drawSelf();
            MatrixState.popMatrix();
            MatrixState.popMatrix();
        }
    }

    class RotateThread extends Thread {
        public boolean flag = true;

        @Override
        public void run() {
            while (flag) {
             //  mRenderer.point_line_shape.updateDrawState();
                MatrixState.rotate(0.5f , 0,0, 1);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void setLightOffset(float lightOffset) {
        this.lightOffset = lightOffset;
    }
}
